/**
 * 应用基础视图
 */
define(['jquery', 'underscore', 'FilterView', 'intro', 'text!templates/pro/prouser_tip.html'],
    function ($, _, FilterView, introJs, prouserTip) {
        var AppView = FilterView.extend({
            el: 'body',
            events: {
                'click                     [data-toggle="screenchange"]': 'changeScreen',
                'click                         [data-toggle="checkall"]': 'checkall',
                'click                       [data-toggle="uncheckall"]': 'uncheckall',
                'click                          [data-toggle="sidebar"]': 'toggleSidebar',
                'change              :checkbox[data-toggle="pagecheck"]': 'togglePageCheck',
                'change                         .checklist    :checkbox': 'changeCheckpageStatus',
                'mouseenter                        [data-toggle="zoom"]': 'zoom',
                'mouseleave                        [data-toggle="zoom"]': 'unzoom',
                'change                  select[data-trigger="refresh"]': 'refreshTarget',
                'click                          [data-toggle="operate"]': 'executeOperate', //执行批量操作
                'click                       [data-toggle="windowopen"]': 'openNewWindow',
                'change                                input.check-bool': 'change',
                'click                                         .read-to': 'toMessageRead',
                'select2:select                         select.has-open': 'openNewWindow',
                'click                               button.open-window': 'openNewWindow',
                'click                            [data-toggle="intro"]': 'startIntro'
            },
            initialize: function () {
                var that = this;
                $('[data-toggle="refresh"]').each(function () {
                    var ignoreFirst = $(this).data('ignore-first') || false;
                    if (!ignoreFirst) {
                        that.refresh($(this));
                    } else {
                        $(this).removeClass('loading');
                    }
                });
                this.listenScreenChange();
                this.initStaticOpenModal();
                this.initDisplay();

                this.prouserTipTpl = _.template(prouserTip);

                if ($('#MigrateFormOms').length > 0 && $('#MigrateFormOms').val().toUpperCase() == 'TRUE') {
                    this.prouserTip();
                } else {
                    if ($('#FirstLogin').length > 0 && $('#FirstLogin').val().toUpperCase() == 'TRUE') {
                        this.startIntro();
                    }
                }
            },
            
            //# pro迁移到lite用户提示
            //
            prouserTip: function () {
                var $page = $('#Page'),
                    username = $('#MigrateFormOms').data('username');
                $page.append(this.prouserTipTpl({ username: username }));

                $('#ProTip').modal('show');

            },
            
            //# 打开新窗口
            //
            openNewWindow: function (event) {
                var $target = $(event.target),
                    that = this;
                switch ($target[0].tagName) {
                    case 'SELECT':
                        var $selectedOption = $target.find('option:selected');
                        if ($selectedOption.hasClass('open')) {
                            var openUrl = $selectedOption.data('open-url'),
                                openName = $selectedOption.data('open-name');
                            if ($target.closest('.modal').length > 0) {
                                that.destoryModal($target.closest('.modal'));
                            }
                            setTimeout(function () {
                                window.open(openUrl, openName);
                            }, 500);
                        }
                        break;
                    case 'BUTTON':
                        var openUrl = $target.data('open-url'),
                            openName = $target.data('open-name');
                        if ($target.closest('.modal').length > 0) {
                            that.destoryModal($target.closest('.modal'));
                        }
                        setTimeout(function () {
                            window.open(openUrl, openName);
                        }, 500);
                        break;

                }

            },
            //# 阅读消息
            //
            toMessageRead: function (event) {
                var $target = $(event.target).closest('.read-to'),
                    url = $target.data('url');

                var w = window.open();
                w.location.href = url;


            },

            initStaticOpenModal: function () {
                var $staticOpenModal = this.$('#StaticOpenModal');
                $staticOpenModal.modal('show');
            },

            //#刷新目标区域
            //
            refreshTarget: function (event) {
                var tagName = event.target.nodeName,
                    params = {},
                    $target = $(event.target),
                    that = this;


                var triggerTarget = $target.data('target'),
                    option = {
                        showLoading: false
                    };
                if (tagName === 'SELECT') {
                    params[$target.attr('name')] = $target.val();
                    _.each(triggerTarget.split(','), function (targetId) {
                        // $(targetId).val('');
                        that.refresh($(targetId), params, option);
                    })
                }
            },

            /**
             * 放大图片
             * @param  {any} event
             * @param  {any} {}
             */
            zoom: function (event) {
                var $target = $(event.target),
                    imgSrc = $target.attr('src');

                $zoomContainer = $('<div>', {
                    class: 'zoom-container'
                });
                $zoomImg = $('<img>', {
                    class: 'zoom-img',
                    src: imgSrc
                });

                $zoomContainer.append($zoomImg);

                $target.after($zoomContainer);
            },
            unzoom: function (event) {
                var $target = $(event.target);

                $target.next('.zoom-container').remove();
            },
            /**
             * 全选
             * @param  {[type]} event [description]
             * @return {[type]}       [description]
             */
            checkall: function (event) {
                event.preventDefault();
                var $target = $(event.target),
                    $checkTarget = $($target.data('target'));

                $checkTarget.find(':checkbox').prop('checked', true);
            },

            /**
             * 取消全选
             * @param  {[type]} event [description]
             * @return {[type]}       [description]
             */
            uncheckall: function (event) {
                event.preventDefault();
                var $target = $(event.target),
                    $checkTarget = $($target.data('target'));

                $checkTarget.find(':checkbox').prop('checked', false);
            },

            //# 执行批量操作
            //
            executeOperate: function (event) {
                event.preventDefault();
                var $target = $(event.target),
                    $operateToggle = $target.closest('[data-toggle="operate"]'),
                    operateMode = $operateToggle.data('operate-mode'),
                    that = this;

                switch (operateMode) {
                    case 'confirm':
                        that.confirmView.getConfirm(event);
                        break;
                    case 'remotemodal':
                        that.getRemoteModal(event);
                        break;
                    case 'newpage':
                        that.openNewPage($operateToggle);
                        break;
                    case 'print':
                        that.print($operateToggle);
                        break;
                    case 'direct': //直接提交
                        that.directOperate($operateToggle);
                        break;
                }
            },

            //# 打印
            //
            print: function ($operateToggle) {
                var $operateTarget = $($operateToggle.data('operate-target')),
                    printUrl = $operateToggle.attr('href'),
                    printBatch = $operateToggle.data('print-batch'),
                    batchData = {},
                    that = this;

                $operateTarget.find('.factor:checked').each(function () {
                    var key = $(this).attr('name');
                    if (!_.isArray(batchData[key])) {
                        batchData[key] = [];
                    }
                    batchData[key].push($(this).val());
                });
                var newOpen = window.open('#', 'printing');
                if (printBatch) {
                    $.ajax({
                        url: printUrl,
                        type: 'post',
                        data: batchData,
                        dataType: 'json'
                    }).done(function (res, status, xhr) {
                        if (res.Errors && !res.Errors.IsValid) {
                            that.errorAlert(res.Errors.ErrorItems[0].ErrorMessage);
                        } else {
                            that.showPrintConfirm($operateToggle, res.Content);
                            newOpen.location.href = xhr.getResponseHeader('Location');
                        }
                    }).fail(function () {
                        that.errorAlert('网络连接超时');
                    }).always(function () {

                    });
                } else {
                    window.open(printUrl + '?' + $.param(batchData, true), 'printing');
                }
            },

            //# 打开新页面处理
            //
            openNewPage: function ($operateToggle) {
                var $operateTarget = $($operateToggle.data('operate-target')),
                    pageUrl = $operateToggle.attr('href'),
                    operateSource = $operateToggle.data('operate-source'),
                    batchData = {},
                    that = this;

                $operateTarget.find('.factor:checked').each(function () {
                    var key = $(this).attr('name');
                    if (!_.isArray(batchData[key])) {
                        batchData[key] = [];
                    }
                    batchData[key].push($(this).val());
                });

                switch (operateSource) {
                    case 'printing':
                        that.showPrintConfirm($operateToggle);
                        break;
                }
                window.open(pageUrl + '?' + $.param(batchData, true), "picking");
            },

            showPrintConfirm: function ($operateToggle, data) {
                require(['text!templates/order/confirm_printing.html'], function (confirmPrinting) {
                    var confirmPrintingTpl = _.template(confirmPrinting),
                        confirmParams = {};
                    if (data) {
                        confirmParams.confirmUrl = $operateToggle.data('confirm-url') + '?' + $.param(data, true);
                    } else {
                        confirmParams.confirmUrl = $operateToggle.data('confirm-url');
                    }

                    confirmParams.successMode = $operateToggle.data('success-mode');

                    $('#Page').append(confirmPrintingTpl(confirmParams));
                    $('#Confirm').modal('show');
                });
            },

            directOperate: function ($operateToggle) {
                var $operateTarget = $($operateToggle.data('operate-target')),
                    pageUrl = $operateToggle.attr('href'),
                    successMessage = $operateToggle.data('success-msg') || '操作成功',
                    batchData = {},
                    that = this;

                $operateTarget.find('.factor:checked').each(function () {
                    var key = $(this).attr('name');
                    if (!_.isArray(batchData[key])) {
                        batchData[key] = [];
                    }
                    batchData[key].push($(this).val());
                });
                $.ajax({
                    url: pageUrl,
                    type: 'post',
                    data: batchData,
                    dataType: 'json'
                }).done(function (res) {
                    if (res.Errors && !res.Errors.IsValid) {
                        that.errorAlert(res.Errors.ErrorItems[0].ErrorMessage);
                    } else {
                        that.refresh($operateTarget, that.generateParams());
                        that.successAlert(successMessage);
                    }
                }).fail(function () {
                    that.errorAlert('网络连接超时');
                }).always(function () {

                });
            },

            /**
             * 切换页面全选状态
             * @param event
             */
            togglePageCheck: function (event) {
                var $target = $(event.target),
                    $checkTarget = this.$($target.data('target')),
                    $checkItems = $checkTarget.find(':checkbox');
                if ($target.is(':checked')) {
                    this.$('[data-toggle="pagecheck"]').prop('checked', true);
                    $checkItems.prop('checked', true);
                    $('.batchoperate').removeClass('disabled');
                } else {
                    this.$('[data-toggle="pagecheck"]').prop('checked', false);
                    $checkItems.prop('checked', false);
                    $('.batchoperate').addClass('disabled');
                }
            },

            /**
             * 选中list中checkbox，判断是否全部选中
             */
            changeCheckpageStatus: function (event) {
                var $target = $(event.target),
                    $operateList = $target.closest('.checklist'),
                    uncheckNumber = 0;
                $operateList.find(':checkbox').each(function () {
                    if (!$(this).is(':checked')) {
                        uncheckNumber += 1;
                    }
                });
                if (uncheckNumber == 0) {
                    $('[data-toggle="pagecheck"]').prop('checked', true);
                } else {
                    $('[data-toggle="pagecheck"]').prop('checked', false);
                }
                if ($operateList.find(':checkbox:checked').length <= 0) {
                    $('.batchoperate').addClass('disabled');
                } else {
                    $('.batchoperate').removeClass('disabled');
                }

            },

            //# 监听
            listenScreenChange: function () {
                var that = this,
                    $maxscreen = that.$('.maxscreen'),
                    $minscreen = that.$('.minscreen');
                document.addEventListener(screenfull.raw.fullscreenchange, function () {
                    that.$('.maxscreen,.minscreen').toggleClass('hide');
                    if ($maxscreen.hasClass('hide')) {
                        $minscreen.closest('a').attr('title', '退出全屏');
                    } else {
                        $maxscreen.closest('a').attr('title', '全屏');
                    }
                });
            },
            changeScreen: function (event) {
                if (screenfull.enabled) {
                    screenfull.toggle();
                }
            },
            toggleSidebar: function (event) {
                var $target = $(event.target),
                    $targetToggle = $target.closest('[data-toggle="sidebar"]'),
                    $targetSidebar = this.$($targetToggle.data('target'));

                $targetSidebar.toggleClass('open');
            },
            //# 获取RmoteModal内容并渲染
            //
            getRemoteModal: function (event) {
                event.preventDefault();

                var $target = $(event.target),
                    $page = $target.closest('#Page'),
                    $toggleTarget = $target.closest('[data-toggle="remotemodal"]'),
                    that = this;

                if ($toggleTarget.length == 0) {
                    $toggleTarget = $target.closest('[data-toggle="operate"]');
                }
                var modalUrl = $toggleTarget.data('modal-url');

                $.ajax({
                    url: modalUrl,
                    type: 'GET',
                    dataType: 'html'
                }).done(function (res) {
                    if ($('#RemoteModal').length > 0) {
                        $('.modal-backdrop').remove();
                        $('#RemoteModal').remove();
                    }
                    $page.append(res);
                    that.initDisplay();

                    var $RemoteModal = that.$('#RemoteModal'),
                        scriptPath = $RemoteModal.data('script-path') || 'ModalView';
                    $RemoteModal.modal({
                        keyboard: false,
                        backdrop: 'static',
                        show: true
                    });

                    require([scriptPath], function (View) {
                        that.remoteView = new View();
                    });
                }).always(function () {
                    $page.removeClass('loading');
                })
                $page.addClass('loading');
            },
        });
        return AppView;
    });
